package com.xyzh05.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xyzh05.dao.EditorDao;
import com.xyzh05.dao.TransactionDao;
import com.xyzh05.model.Editor;
import com.xyzh05.model.Order;
import com.xyzh05.model.Transaction;
import com.xyzh05.model.TransactionEntry;
import com.xyzh05.model.User;
import com.xyzh05.service.TransactionManager;
import com.xyzh05.util.PageBean;

@Service("transactionManager")
@WebService(serviceName = "TransactionService", endpointInterface = "com.xyzh05.service.TransactionManager")
public class TransactionManagerImpl extends GenericManagerImpl<Transaction, Long> implements TransactionManager {
    TransactionDao transactionDao;
    
    private EditorDao editorDao ; 

    @Autowired
    public TransactionManagerImpl(TransactionDao transactionDao) {
        super(transactionDao);
        this.transactionDao = transactionDao;
    }
    
    
    
    public TransactionDao getTransactionDao() {
		return transactionDao;
	}



	public void setTransactionDao(TransactionDao transactionDao) {
		this.transactionDao = transactionDao;
	}



	public EditorDao getEditorDao() {
		return editorDao;
	}



	public void setEditorDao(EditorDao editorDao) {
		this.editorDao = editorDao;
	}



	/**
	 * 创建文书交易
	 * @param client 定单客户
	 * @param orders 文书定单
	 * @param state 交易状态。新交易: Transaction.NEW, 未支付: Transaction.PAY, 已支付: Transaction.START
	 * @return
	 * @throws Exception 编辑空闲点数不够
	 */
	public Transaction checkout(User client, List<Order> orders, int state) throws Exception {
		// 检查编辑空闲点数
		Map<Editor, Integer> points = new HashMap<Editor, Integer>();
		for (Order order : orders) {
			if (!points.containsKey(order.getEditor()))
				points.put(order.getEditor(), 0);
			Integer totalPoint = points.get(order.getEditor());
			totalPoint += order.getPricing().getService().getPoint();
			if (totalPoint > order.getEditor().getRemainIdle()) {
				// 超出空闲点数，无法购买
				throw new Exception("NOT_ENOUGH_IDLE");
			}
			points.put(order.getEditor(), totalPoint);
		}
		
		// TODO:更新编辑空闲点数
		for (Editor editor : points.keySet()) {
			editor.setRemainIdle(editor.getRemainIdle() - points.get(editor));
			editorDao.saveOrUpdate(editor);
		}
		
		// 生成交易
		Calendar calendar = Calendar.getInstance();
		Date startTime = calendar.getTime();
		int maxPeriod=0;
		Double totalPay = 0D;
		List<TransactionEntry> entries = new ArrayList<TransactionEntry>();
		
		for (Order order : orders) {
			TransactionEntry entry = new TransactionEntry();
			
			//TODO: 设置编辑关系
			entry.setEditor(order.getEditor());
			entry.setStartTime(startTime);
			entry.setFinishTime(startTime);
			
			// TODO
			// 修改：陶承恺
			// deadline为当前时间+服务时间+反馈时间
			calendar = Calendar.getInstance();
			calendar.add(Calendar.DATE, Integer.parseInt ( order.getPricing().getService().getPeriod()+order.getPricing().getService().getModifyPeriod().toString()));
			Date deadline = calendar.getTime();
			if((order.getPricing().getService().getPeriod()+order.getPricing().getService().getModifyPeriod())>maxPeriod)
			{
				maxPeriod= Integer.parseInt (order.getPricing().getService().getPeriod()+order.getPricing().getService().getModifyPeriod().toString());
			}

			entry.setDeadline(deadline);
			// TODO 设置编辑所得款
			Double payment = order.getPricing().getPrice();
			if (order.getPricing().getService().getStepPrice() > 0) {
				if (order.getSchoolNum() < 2)
					order.setSchoolNum(2);
				payment += order.getPricing().getService().getStepPrice() * (order.getSchoolNum() - 1);
			}
			entry.setPayment(payment);
			entry.setSchoolNum(new Long(order.getSchoolNum()));
			
			entry.setService(order.getPricing().getService());
			entry.setUser(client);
			entry.setFinished(false);
			entry.setStep(new Long(state));
			//entry.setTransaction(transaction);
			entries.add(entry);
			totalPay += entry.getPayment();
		}

		Transaction transaction = new Transaction();
		transaction.setStatus(new Long(state));
		transaction.setPayed(state == Transaction.START);
		transaction.setPayType(1);
		transaction.setPayment(totalPay);
		transaction.setUser(client);
		transaction.setStartTime(startTime);
		calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, maxPeriod);
		Date deadline = calendar.getTime();
		transaction.setDeadline(deadline);
		transaction.setEntries(entries);
		transaction.setShowId(Order.newOrderId());
		transactionDao.save(transaction);
		
		return transaction;
	}



	public PageBean findList(PageBean pageBean, Transaction transaction) {
		StringBuilder sb = new StringBuilder();
		List list = new ArrayList();
		sb.append(" from Transaction vs where 1 = 1 ");
		
		
		if(pageBean != null){
			if (pageBean.getSortCriterion() != null) {
				sb.append(" order by ");
				sb.append(pageBean.getSortCriterion()+" ");			
			}
			if (pageBean.getSortParamDirection() != null) {
				sb.append(pageBean.getSortParamDirection());			
			}
		}
		
		return transactionDao.getPageByHQL(sb.toString(), pageBean, list.toArray());
	}
}